package com.star.mall.controller;

import cn.hutool.core.util.StrUtil;
import com.star.mall.base.model.AuthResponse;
import com.star.mall.base.response.BaseResponse;
import com.star.mall.base.response.ResponseCode;
import com.star.mall.handler.JwtTokenHandler;
import com.star.mall.model.PasswordParam;
import com.star.mall.model.UserDetail;
import com.star.mall.persistence.service.IUserService;
import com.star.mall.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 认证接口
 * @author StarQ
 * @since 2021-04-16
 */
@RestController
@RequestMapping("/api/v1")
@Api(value = "登录认证", tags = {"登录认证"})
public class AuthController {

    @Resource
    AuthService authService;
    @Resource
    IUserService userService;
    @Resource
    JwtTokenHandler jwtTokenHandler;

    @Value("${jwt.expiration}")
    private Long expiration;

    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST")
    public BaseResponse<AuthResponse> login(@ApiParam(name="userDetail", value = "登录账号密码", required = true) @RequestBody UserDetail userDetail) {
        String token = authService.login(userDetail.getUsername(), userDetail.getPassword());
        if (StrUtil.isEmpty(token)) {
            return new BaseResponse<>(ResponseCode.VALIDATE_ERROR,"认证失败",null);
        }
        return new BaseResponse<>(ResponseCode.SUCCESS,"认证成功", new AuthResponse(token, expiration));
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "退出登录", httpMethod = "GET")
    public BaseResponse<String> logout() {
        return BaseResponse.success("退出成功");
    }

    @PostMapping("/password/update")
    @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST")
    public BaseResponse<String> modifyPassword(@ApiParam(name = "password", value = "旧密码与新密码") @Validated @RequestBody PasswordParam passwordParam) {
        return userService.modifyPassword(passwordParam);
    }

    @GetMapping("/token/refresh")
    @ApiOperation(value = "刷新token", notes = "刷新token", httpMethod = "GET")
    public BaseResponse<AuthResponse> refresh(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        String accessToken = jwtTokenHandler.refreshAccessToken(token);
        return new BaseResponse<>(ResponseCode.SUCCESS, new AuthResponse(accessToken, expiration));
    }

}
